// packageA/components/videoControls/index.js
Component({
  externalClasses: ['custom-class'],
  /**
   * 组件的属性列表
   */
  properties: {
    currentTime: {
      type: Number,
      value: 0
    }, 
    duration: {
      type: Number,
      value: 0
    },
    showProgress: {
      type: Boolean,
      value: true
    }
  },
  observers: {
    currentTime(value) {
      if (!this.insideMove) {
        this.setData({
          curTime: value,
          x: this.calcX(value)
        })
      }
    },
    showProgress(value) {
      if (value && !this.data.show) {
        this.showControls()
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    x: 0,
    curTime: 0,
    show: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    showControls() {
      clearTimeout(this.showTimer)

      this.setData({
        show: true
      }, () => {
        this.showTimer = setTimeout(() => {
          this.setData({
            show: false
          })
          this.triggerEvent('controlstoggle', {
            show: false
          })
        }, 6000)
      })
    },
    calcX(curTime = 0) {
      let {duration = 1} = this.properties, progressWidth = this.progressWidth || 0;
      duration = duration || 1;
      let percent = curTime / duration

      progressWidth = Math.floor(progressWidth * percent)
      progressWidth = progressWidth > this.progressWidth ? this.progressWidth : progressWidth

      return progressWidth
    },
    calcTime(x = 0) {
      let {duration = 0} = this.properties,
        progressWidth = this.progressWidth || 1;
      let percent = x / progressWidth
      return (duration * percent) 
    },
    touchStartHandle() {
      this.insideMove = true
      clearTimeout(this.showTimer)
      this.setData({show: true})
    },
    touchEndHandle() {
      this.insideMove = false
      if (this.data.curTime != this.properties.currentTime) {
        this.triggerEvent('move', this.data.curTime)
      }
      this.showControls()
    },
    positionChangeHandle(event) {
      const {x, source} = event.detail
      if (source == 'touch') {
        let time = this.calcTime(x)
        this.setData({
          x,
          curTime: time
        })
      }
    },
    controlsTapHandle() {
      this.triggerEvent('controlstoggle', {
        show: true
      })
    },
    catchTouchMove() {
      return false
    }
  },
  ready() {
    const that = this
    const query = wx.createSelectorQuery().in(this)
    query.select('#progressBar').boundingClientRect(function(rect){
      that.progressWidth = Math.floor(rect.width)
    }).exec()
  }
})
